package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
	"time"
)

type Reader interface {
	read(rc chan []byte)
}

type Writer interface {
	write(wc chan string)
}

type ReadFromFile struct {
	path string
}

func (r *ReadFromFile) read(rc chan []byte) {

	// 打开文件
	file, err := os.Open(r.path)
	if err != nil {
		panic(fmt.Sprintf("open file err:%s", err.Error()))
	}

	file.Seek(0, 2)

	// 到文件末尾一行 逐行读取文件内容
	rd := bufio.NewReader(file)

	for {
		data, err := rd.ReadBytes('\n')
		if err == io.EOF {
			time.After(500 * time.Millisecond)
			continue
		} else if err != nil {
			panic(fmt.Sprintf("open file err:%s", err.Error()))
		}

		// 写入到 rc
		rc <- data[:len(data)-1]
	}

}

type WriteToInfluxDb struct {
	influxDb string
}

func (w *WriteToInfluxDb) write(wc chan string) {
	for {
		fmt.Println(<-wc)
	}
}

// 读取器
type LogProcess struct {
	read  Reader
	write Writer
	rc    chan []byte
	wc    chan string
}

func (l *LogProcess) Process() {
	for {
		msg := <-l.rc
		l.wc <- strings.ToUpper(string(msg))
	}

}

func main() {

	r := &ReadFromFile{
		path: "./access.log",
	}

	w := &WriteToInfluxDb{
		influxDb: "asd@123",
	}

	l := &LogProcess{
		rc:    make(chan []byte),
		wc:    make(chan string),
		read:  r,
		write: w,
	}

	go l.read.read(l.rc)
	go l.Process()
	go l.write.write(l.wc)

	// time.After(1 * time.Second)
	select {
	case <-time.After(30 * time.Second):
		fmt.Println("end")
	}
}
